#include "ResMgrPch.h"

#include "RenderFacade.h"
#include "Texture.h"
#include "ResourceManager.h"
#include "TextureManager.h"

TextureManager::TextureManager( ResourceManager * resourceManager ) :
m_owner( resourceManager )
{
	m_hmapTexture.clear();
}

TextureManager::~TextureManager()
{
}

void TextureManager::Init()
{
}

void TextureManager::UnInit()
{
	stdext::hash_map< std::string, Texture* >::iterator Begin = m_hmapTexture.begin();

	for(; Begin != m_hmapTexture.end(); ++Begin )
	{
		SAFE_DELETE( Begin->second );
	}

	m_hmapTexture.clear();
}

Texture * TextureManager::CreateTexture( const char* resID, BOOL mipGenerate )
{
	stdext::hash_map< std::string, Texture* >::iterator it = m_hmapTexture.find( resID );
	if( it != m_hmapTexture.end() )
	{
		Texture * pTexture = it->second;
		pTexture->AddRef();

		return pTexture;
	}

	BinaryMemory mem;
	if( m_owner->ReadBinaryFileToMemory(mem, resID) == FALSE )
	{
		return NULL;
	}

	D3DXIMAGE_INFO imageInfo;
	D3DXGetImageInfoFromFileInMemory(mem.GetMemory(), mem.GetMemorySize(), &imageInfo );

	D3DFORMAT format = D3DFMT_R8G8B8;
	UINT MipLevel = D3DX_DEFAULT;
	if( mipGenerate == FALSE )
	{
		MipLevel = 1;
	}

	LPDIRECT3DTEXTURE9 d3dTexture = NULL;
	if( FAILED(D3DXCreateTextureFromFileInMemoryEx(RenderFacade::GetInstance()->GetDxDevice()
		, mem.GetMemory()
		, mem.GetMemorySize()
		, imageInfo.Width
		, imageInfo.Height
		, MipLevel
		, 0
		, format
		, D3DPOOL_MANAGED
		, D3DX_FILTER_NONE
		, D3DX_FILTER_NONE
		, 0
		, NULL
		, NULL
		, &d3dTexture
		)))
	{
		return NULL;
	}

	Texture * pTexture = new Texture();
	pTexture->SetResourceName( resID );
	pTexture->Set( d3dTexture );
	pTexture->AddRef();

	m_hmapTexture[resID] = pTexture;

	return pTexture;
}

void TextureManager::ReleaseTexture( const char* resID )
{
	stdext::hash_map< std::string, Texture* >::iterator it = m_hmapTexture.find( resID );
	if( it != m_hmapTexture.end() )
	{
		Texture * pTexture = it->second;
		pTexture->SubRef();

		if( pTexture->GetRef() <= 0 )
		{
			SAFE_DELETE( pTexture );
			m_hmapTexture.erase( it );
		}
	}
}